package com.bluetrum.abmate.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.bluetrum.abmate.R;
import com.bluetrum.abmate.databinding.LayoutDevicePresentationBinding;
import com.bluetrum.abmate.databinding.LayoutQuickPairBottomSheetBinding;
import com.bluetrum.abmate.viewmodels.SharedViewModel;
import com.bluetrum.devicemanager.models.ABDevice;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import dagger.hilt.android.qualifiers.ApplicationContext;

@AndroidEntryPoint
public class BottomSheetQuickPairDialogFragment extends BottomSheetDialogFragment
        implements PopupMenu.OnMenuItemClickListener {

    private static final String PREPARE_DEVICE = "PREPARE_DEVICE";

    // todo: 挪到专门类
    private static final long BLOCK_TIME_TEMP       = 0;
    private static final long BLOCK_TIME_FOREVER    = -1;
    private static final long BLOCK_TIME_ONE_DAY    = 24 * 60 * 60 * 1000;
    private static final long BLOCK_TIME_ONE_HOUR   = 60 * 60 * 1000;

    private LayoutQuickPairBottomSheetBinding binding;
    private LayoutDevicePresentationBinding layoutDevicePresentationBinding;

    @Inject
    @ApplicationContext
    Context mContext;

    private SharedViewModel mViewModel;

    private final ABDevice preparingDevice;

    public BottomSheetQuickPairDialogFragment(@NonNull ABDevice device) {
        super();
        preparingDevice = device;
    }

//    @NonNull
//    @Override
//    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
//        // Workaround. Now can't tell the way to dismiss
//        Dialog dialog = super.onCreateDialog(savedInstanceState);
//        // Disable touch outside to dismiss
//        dialog.setCanceledOnTouchOutside(false);
//        // Disable drag to dismiss
//        dialog.setOnShowListener(dialog1 -> {
//            View bottomSheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
//            if (bottomSheet != null) {
//                BottomSheetBehavior<View> behavior = BottomSheetBehavior.from(bottomSheet);
//                behavior.setDraggable(false);
//            }
//        });
//        return dialog;
//    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mViewModel = new ViewModelProvider(this).get(SharedViewModel.class);
        binding = LayoutQuickPairBottomSheetBinding.inflate(inflater, container, false);

        layoutDevicePresentationBinding = binding.layoutDevicePresentation;

        binding.connectButton.setOnClickListener(this::clickConnect);
        binding.cancelButton.setOnClickListener(this::clickCancel);
        binding.showMoreBlockTimeButton.setOnClickListener(this::showMoreBlockTime);

        binding.deviceAddress.setText(getIdentifierFromDevice(preparingDevice));

        return binding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        showConnectView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    // 设备标识 = 设备名 + 经典蓝牙地址后两字节
    private String getIdentifierFromDevice(ABDevice device) {
        String address = device.getAddress().replaceAll("[:]", "");
        String identifier = address.substring(address.length() - 4);
        return String.format("%s(%s)", device.getName(), identifier);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        // 清除当前正在处理的设备
        mViewModel.getDeviceRepository().clearPopupDevice();
    }

    private void showConnectView() {
        layoutDevicePresentationBinding.getRoot().setVisibility(View.VISIBLE);
        binding.progressIndicator.setVisibility(View.INVISIBLE);
        binding.connectView.setVisibility(View.VISIBLE);
        binding.connectingView.setVisibility(View.INVISIBLE);
    }

    private void showConnectingView() {
        layoutDevicePresentationBinding.getRoot().setVisibility(View.INVISIBLE);
        binding.progressIndicator.setVisibility(View.VISIBLE);
        binding.connectView.setVisibility(View.INVISIBLE);
        binding.connectingView.setVisibility(View.VISIBLE);
    }

    private void clickConnect(View view) {
        // 配对设备
        mViewModel.getDeviceRepository().bondDevice(preparingDevice);
        showConnectingView();

        dismiss();
    }

    private void clickCancel(View view) {
        // 执行暂时不弹窗
        mViewModel.getDeviceRepository().addDeviceToBlocklist(preparingDevice.getAddress(), BLOCK_TIME_TEMP);
        dismiss();
    }

    private void showMoreBlockTime(View view) {
        PopupMenu popup = new PopupMenu(requireContext(), view);
        popup.setOnMenuItemClickListener(this);
        popup.inflate(R.menu.menu_block_time);
        popup.show();
    }

    // 屏蔽时间菜单
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Long blockTime = null;
        int itemId = item.getItemId();
        if (itemId == R.id.block_forever) {
            blockTime = BLOCK_TIME_FOREVER;
        } else if (itemId == R.id.block_one_day) {
            blockTime = BLOCK_TIME_ONE_DAY;
        } else if (itemId == R.id.block_one_hour) {
            blockTime = BLOCK_TIME_ONE_HOUR;
        }
        if (blockTime != null) {
            mViewModel.getDeviceRepository().addDeviceToBlocklist(preparingDevice.getAddress(), blockTime);
            dismiss();
            return true;
        }
        return false;
    }

}
